﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Delay;

namespace lfm.Parser
{
    internal class Chart
    {
        public static async Task<List<lfm.Artist>> getTopArtists(String e)
        {
            List<lfm.Artist> result = new List<lfm.Artist>();

            // Make Method Run Asynchronously
            await Task.Run(() =>
            {
                XDocument x = XDocument.Parse(e);

                // Parse main artist details
                var results = from u in x.Descendants("artist")
                              select new lfm.Artist
                              {
                                  Name = u.SafeGetElement("name").SafeGetStringValue(),
                                  ImageSmall = u.Elements("image").Where(n => n.SafeGetAttribute("size").SafeGetStringValue() == "small").FirstOrDefault().SafeGetUriValue(),
                                  ImageMedium = u.Elements("image").Where(n => n.SafeGetAttribute("size").SafeGetStringValue() == "medium").FirstOrDefault().SafeGetUriValue(),
                                  ImageLarge = u.Elements("image").Where(n => n.SafeGetAttribute("size").SafeGetStringValue() == "large").FirstOrDefault().SafeGetUriValue(),
                                  ImageExtraLarge = u.Elements("image").Where(n => n.SafeGetAttribute("size").SafeGetStringValue() == "extralarge").FirstOrDefault().SafeGetUriValue(),
                                  ImageMega = u.Elements("image").Where(n => n.SafeGetAttribute("size").SafeGetStringValue() == "mega").FirstOrDefault().SafeGetUriValue(),
                                  Url = u.SafeGetElement("url").SafeGetUriValue(),
                                  Listeners = u.SafeGetElement("stats").SafeGetElement("listeners").SafeGetInt64Value(),
                                  Playcount = u.SafeGetElement("stats").SafeGetElement("playcount").SafeGetInt64Value(),
                                  Streamable = Converters.ToBool(u.SafeGetElement("streamable").SafeGetStringValue()),
                                  PercentageChange = u.SafeGetElement("percentagechange").SafeGetStringValue()
                              };

                foreach (lfm.Artist r in results) result.Add(r);
            });

            // return the full artists
            return result;
        }
    }
}
